﻿using UnityEngine;

public class DisplayUtility
{
    public static Rect GetSubRect(Rect rect, Rect subRatio)
    {
        float newX = rect.x + rect.width * subRatio.x;
        float newY = rect.y + rect.height * subRatio.y;
        float newWidth = rect.width * subRatio.width;
        float newHeight = rect.height * subRatio.height;
        return new Rect(newX, newY, newWidth, newHeight);
    }
    public static Rect CutRectToRatio(Rect rect, float whRatio)
    {
        float currentWHRatio = rect.width / rect.height;
        if (currentWHRatio >= whRatio)
        {
            float fixRatio = whRatio / currentWHRatio;
            // 现在的比要求的更宽
            float newX = rect.x + rect.width * (1 - fixRatio) * 0.5f;
            float newY = rect.y;
            float newWidth = rect.width * fixRatio;
            float newHeight = rect.height;
            return new Rect(newX, newY, newWidth, newHeight);
        }
        else
        {
            // 现在的比要求的更高
            float fixRatio = currentWHRatio / whRatio;
            float newX = rect.x;
            float newY = rect.y + rect.height * (1 - fixRatio) * 0.5f;
            float newWidth = rect.width;
            float newHeight = rect.height * fixRatio;
            return new Rect(newX, newY, newWidth, newHeight);
        }

    }
    public static Rect ScreenToWorld(Rect rect)
    {
        Camera cam = Camera.main;
        Vector2 worldMin = cam.ScreenToWorldPoint(rect.min);
        Vector2 worldMax = cam.ScreenToWorldPoint(rect.max);
        return new Rect(worldMin, worldMax -  worldMin);
    }
    public static Rect ScreenToView(Rect rect)
    {
        return new Rect(rect.x / Screen.width, rect.y / Screen.height, rect.width / Screen.width, rect.height / Screen.height);
    }
    public static SpriteRenderer CreateSpriteObject(Sprite sprite, Rect screenRect)
    {
        GameObject obj = new GameObject(sprite.name);
        SpriteRenderer sr = obj.AddComponent<SpriteRenderer>();
        sr.sprite = sprite;
        sr.drawMode = SpriteDrawMode.Sliced;

        Rect worldRect = DisplayUtility.ScreenToWorld(screenRect);

        obj.transform.position = worldRect.center;
        sr.size = worldRect.size;

        return sr;
    }
    public static bool IsInScreen(RectTransform rectTransform)
    {
        // 获取UI组件的四个角的世界坐标
        Vector3[] corners = new Vector3[4];
        rectTransform.GetWorldCorners(corners);

        // 判断四个角是否在屏幕可见范围内
        bool isVisible = false;
        foreach (Vector3 corner in corners)
        {
            Vector3 viewportPoint = Camera.main.ScreenToViewportPoint(corner);
            if (viewportPoint.x >= 0 && viewportPoint.x <= 1 && viewportPoint.y >= 0 && viewportPoint.y <= 1)
            {
                isVisible = true;
                break;
            }
        }

        return isVisible;
    }
}